import service from '../require/request';
import { LoginResponse } from './types';
import { permissionChangeEvent } from '../contexts/PermissionContext';

/**
 * 用户登录
 * @param username 用户名
 * @param password 密码
 * @returns Promise<LoginResponse>
 */
export const login = async (username: string, password: string): Promise<LoginResponse> => {
    try {
        const data = await service.post<LoginResponse, LoginResponse>('/b/sme/cdc/career/login', {
            username,
            password
        });

        // 登录成功，保存用户信息和token到本地存储
        localStorage.setItem('token', data.token);
        localStorage.setItem('displayname', data.display_name);
        localStorage.setItem('uid', data.uid);
        localStorage.setItem('userInfo', JSON.stringify(data));

        // 触发权限变更事件，通知权限上下文更新
        window.dispatchEvent(permissionChangeEvent);

        return data;
    } catch (error) {
        console.error('登录请求失败:', error);
        throw error;
    }
};
